<template>
  <div class="zero">
    <div id="mapContainer" class="zero_map">
      <div class="controls">
        <button @click="togglePlay">{{ isPlaying ? '暂停' : '播放' }}</button>
        <input type="range" v-model="currentTime" min="0" :max="totalTime" step="1">
        <select v-model="playbackSpeed">
          <option value="1">1x</option>
          <option value="2">2x</option>
          <option value="4">4x</option>
        </select>
        <select v-model="viewMode">
          <option value="follow">跟随视角</option>
          <option value="overview">全局视角</option>
          <option value="firstPerson">第一人称</option>
        </select>
      </div>
      <!-- <div class="order-info" v-if="currentOrder">
        <h3>订单信息</h3>
        <p>餐厅：{{ currentOrder.restaurant }}</p>
        <p>顾客：{{ currentOrder.customer }}</p>
        <p>剩余时间：{{ estimatedTime }}秒</p>
      </div> -->
    </div>
  </div>
</template>

<script setup lang="ts" name="MapView">
import { onMounted, onUnmounted, ref, watch } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'
let map: any | null = null
let globalAMap: any | null = null

interface MapConfig {
  zoom: number
  center: [number, number]
  viewMode?: string
  pitch?: number
  rotation?: number
}
// 模拟城市数据
const cityData = [
  { name: '市政大厅', position: [116.397428, 39.90923], info: '政府办公大楼' },
  { name: '中央公园', position: [116.403322, 39.914255], info: '城市中心绿地公园' },
  { name: '交通枢纽', position: [116.412145, 39.910281], info: '地铁换乘中心' }
]



// 路径数据示例
const deliveryPath = [
  { lng: 116.397428, lat: 39.90923, timestamp: 0 },   // 餐厅位置
  { lng: 116.400428, lat: 39.91023, timestamp: 5 },
  { lng: 116.403428, lat: 39.91223, timestamp: 10 },
  { lng: 116.407428, lat: 39.91423, timestamp: 15 },  // 顾客位置
]

const mapContainer = ref<HTMLElement | null>(null)
const riderMarker = ref<any>(null)
const pathPolyline = ref<any>(null)
const currentTime = ref(0)
const isPlaying = ref(false)
const playbackSpeed = ref(1)
const viewMode = ref<'follow' | 'overview' | 'firstPerson'>('follow')
let animationFrameId: number

// 计算总时间
const totalTime = deliveryPath[deliveryPath.length - 1].timestamp
onMounted(() => {
  initMapHandle()
})
onUnmounted(() => {
  map?.destroy()
})
const initMapHandle = () => {
  window._AMapSecurityConfig = {
    securityJsCode: 'da7e0385e74db1b4b7c7694d5865c144'
  }
  AMapLoader.load({
    key: 'bd85505cd6f68401989b0fdc385489b6', // 申请好的Web端开发者Key，首次调用 load 时必填
    version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ['AMap.Scale'] //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
  })
    .then((AMap) => {
      globalAMap = AMap
      map = new AMap.Map('mapContainer', {
        // 设置地图容器id
        viewMode: '3D', // 是否为3D地图模式
        zoom: 11, // 初始化地图级别
        mapStyle: 'amap://styles/whitesmoke',
        pitch: 60,  // 俯仰角度
        rotation: -35,  // 地图旋转角度
        center: [116.397428, 39.90923] // 初始化地图中心点位置
      } as MapConfig)

      // 添加3D建筑
      map.setFeatures(['bg', 'building'])

      // 添加标记
      // addMarkers()

      // // 添加热力图
      // addHeatmap()

      // // 添加地图控件
      // addControls()


      // 创建骑手标记
      riderMarker.value = new AMap.Marker({
        position: deliveryPath[0],
        icon: new AMap.Icon({
          image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_bs.png',
          size: new AMap.Size(32, 32)
        }),
        offset: new AMap.Pixel(-16, -32)
      })

      // 创建路径线
      pathPolyline.value = new AMap.Polyline({
        path: deliveryPath.map(p => [p.lng, p.lat]),
        strokeColor: "#3366FF",
        strokeWeight: 4,
        lineCap: 'round'
      })

      map.add([pathPolyline.value, riderMarker.value])

    })
    .catch((e) => {
      console.error(e)
    })
}
// 使用高德路径规划API获取真实路径
// const planRoute = async (start: globalAMap.LngLat, end: globalAMap.LngLat) => {
//   return new Promise((resolve: any) => {
//     AMap.plugin('AMap.Driving', () => {
//       const driving = new AMap.Driving()
//       driving.search(start, end, (status: string, result: any) => {
//         if (status === 'complete') {
//           const path = result.routes[0].steps.flatMap((step: any) =>
//             step.path.map((p: any) => ({
//               lng: p.lng,
//               lat: p.lat,
//               timestamp: 0 // 需要计算时间戳
//             }))
//           resolve(path)
//         }
//       })
//     })
//   })
// }
// 添加交通图层
// const addTrafficLayer = () => {
//   const trafficLayer = new globalAMap.TileLayer.Traffic({
//     autoRefresh: true,
//     interval: 300
//   })
//   trafficLayer.setMap(map.value)
// }

// 在路径规划时考虑实时路况
// const driving = new globalAMap.Driving({
//   map: map.value,
//   policy: globalAMap.DrivingPolicy.REAL_TRAFFIC
// })
// 计算当前路径位置
const getCurrentPosition = (time: number) => {
  let startIndex = deliveryPath.findIndex(p => p.timestamp >= time) - 1
  if (startIndex < 0) startIndex = 0
  const endIndex = startIndex + 1

  const start = deliveryPath[startIndex]
  const end = deliveryPath[endIndex]
  const progress = (time - start.timestamp) / (end.timestamp - start.timestamp)

  return {
    lng: start.lng + (end.lng - start.lng) * progress,
    lat: start.lat + (end.lat - start.lat) * progress
  }
}

// 更新视角
const updateView = (position: { lng: number; lat: number }) => {
  switch (viewMode.value) {
    case 'follow':
      map.value.setCenter(position)
      map.value.setRotation(-45)
      map.value.setPitch(60)
      break
    case 'overview':
      map.value.setFitView([pathPolyline.value])
      break
    case 'firstPerson':
      map.value.setCenter(position)
      map.value.setRotation(0)
      map.value.setPitch(0)
      break
  }
}

// 动画循环
const animate = () => {
  if (!isPlaying.value) return

  const nextTime = currentTime.value + 0.1 * playbackSpeed.value
  currentTime.value = Math.min(nextTime, totalTime)

  const position = getCurrentPosition(currentTime.value)
  riderMarker.value.setPosition(position)
  updateView(position)

  if (currentTime.value < totalTime) {
    animationFrameId = requestAnimationFrame(animate)
  } else {
    isPlaying.value = false
  }
}

const togglePlay = () => {
  isPlaying.value = !isPlaying.value
  if (isPlaying.value) animate()
}

watch(currentTime, (newTime) => {
  const position = getCurrentPosition(newTime)
  riderMarker.value.setPosition(position)
  updateView(position)
})

// // 添加地图标记
// const addMarkers = () => {
//   cityData.forEach(point => {
//     const marker = new globalAMap.Marker({
//       position: point.position,
//       content: `<div class="marker">
//                   <div class="marker-icon"></div>
//                   <div class="marker-label">${point.name}</div>
//                 </div>`,
//       offset: new globalAMap.Pixel(-15, -45)
//     })

//     // 添加信息窗口
//     const infoWindow = new globalAMap.InfoWindow({
//       content: `<div class="info-window">
//                   <h3>${point.name}</h3>
//                   <p>${point.info}</p>
//                 </div>`,
//       offset: new globalAMap.Pixel(0, -40)
//     })

//     marker.on('click', () => {
//       infoWindow.open(map, point.position)
//     })

//     map.add(marker)
//   })
// }

// // 添加热力图
// const addHeatmap = () => {
//   const heatmapData = [
//     { lng: 116.397428, lat: 39.90923, count: 80 },
//     { lng: 116.407428, lat: 39.90923, count: 30 },
//     { lng: 116.417428, lat: 39.90923, count: 50 }
//   ]

//   const heatmap = new globalAMap.HeatMap(map, {
//     radius: 30,  // 热力半径
//     opacity: [0.4, 0.8],  // 透明度范围
//     gradient: {  // 颜色梯度
//       0.4: 'blue',
//       0.6: 'yellow',
//       0.8: 'orange',
//       1.0: 'red'
//     }
//   })

//   heatmap.setDataSet({
//     data: heatmapData,
//     max: 100
//   })
// }

// // 添加地图控件
// const addControls = () => {
//   map.addControl(new globalAMap.Scale())  // 比例尺
//   map.addControl(new globalAMap.ToolBar({   // 工具条
//     position: { top: '10px', right: '10px' }
//   }))
// }



</script>

<style scoped lang="less">
@Color: rgb(0, 72, 216);

// 在样式中添加
.order-info {
  position: fixed;
  top: 20px;
  right: 20px;
  background: white;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.controls {
  position: fixed;
  top: 20px;
  left: 20px;
  z-index: 1000;
  background: rgba(255, 255, 255, 0.9);
  padding: 10px;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  display: flex;
  gap: 10px;
}

.controls button {
  padding: 5px 10px;
  cursor: pointer;
}

.controls input[type="range"] {
  width: 200px;
}

.controls select {
  padding: 5px;
}

.zero {
  width: 100%;
  height: 100%;
  position: relative;

  .zero_map {
    position: absolute;
    width: 100%;
    height: 100%;
  }

  .options {
    position: absolute;
    right: 0;
    bottom: 0;
    background: #ffffff;
    padding: 8px;
    border-radius: 6px;
    box-shadow: rgba(0, 0, 0, 0.5) 2px 3px 3px;
  }
}
</style>
